<template>
  <view class="container">
    <view style="height: var(--status-bar-height)"></view>
    <!-- 自定义导航栏 -->
    <MapNav
      ref="mapNavRef"
      v-model:model-value-show-category="showCategory"
      v-model:model-value-show-my-center="showMyCenter"
      v-model:model-value-show-my-order="showMyOrder"
      v-model:model-value-show-my-checkout="showMyCheckout"
      v-model:model-value-setting-checkout="showMySetting"
      v-model:model-value-my-position="showMyPosition"
    />
    <!-- 搜索框 -->
    <settingPopup ref="settingPopupRef" />
    <PointPopup ref="pointPopupRef" @onSearchFor="geodeticSearchFor" />
    <LotglaListPopup ref="lotglaListPopupRef" @onSearchFor="lotglaListSearchFor"/>

    <SearchPopup ref="searchPopupRef" @click="handleSearchClick" @sClick="handleSearchSClick"/>
    <OrderPopup ref="orderPopupRef" @click="handleOrderClick" />
    <CartPopup ref="cartPopupRef" @click="handleCartClick" />

    <GeodeticMap ref="mapRef" @click="handleMapClick" @mclick="handleMapMClick" @tclick="handlePositionTClick" @locationDetails="handleLocationDetails" />

    <GeodeticPopup ref="geodeticRef" @click="handleGeodeticClick" />
    <Hk1980Popup ref="hk1980Ref" @click="handleHk1980Click" />
    <LotglaPopup ref="lotglaRef" @click="handleLotglaClick" />

    <tooltip ref="tooltipRef" @click="handleTooltipClick"></tooltip>

    <positionPopup ref="positionRef" :searchList="searchList" @click="handlePositionClick" @tclick="handlePositionTClick"></positionPopup>

    <LocationDetailsPopup ref="locationDetailsRef"></LocationDetailsPopup>
    <RealTimeInfoPopup ref="realTimeInfoRef"></RealTimeInfoPopup>

    <up-loading-page :loading="uploading" bg-color="#e8e8e842" :zIndex="1000000" loading-mode="spinner"></up-loading-page>
  </view>
</template>

<script lang="ts" setup>
import { ref, onMounted, watch,nextTick } from 'vue'
import { onLoad, onShow, onHide } from '@dcloudio/uni-app'
import { useUserStore } from '@/stores'
import { HKMAPsearch,HKMAPlotglaByPid } from '@/api/system/map'
import GeodeticMap from '@/components/IMapPane/index.vue'
import MapNav from '@/pages/common/head/index.vue'
import settingPopup from '@/pages/common/head/setting.vue'
import SearchPopup from '@/pages/common/search/index.vue'
import OrderPopup from '@/pages/common/order/index.vue'
import CartPopup from '@/pages/common/cart/index.vue'
import PointPopup from '@/pages/common/point/index.vue'

import GeodeticPopup from '@/pages/common/search/geodetic.vue'
import Hk1980Popup from '@/pages/common/search/hk1980.vue'
import LotglaPopup from '@/pages/common/search/lotgla.vue'
import LotglaListPopup from '@/pages/common/search/lotglaList.vue'
import tooltip from '@/components/tooltip/index.vue'
import positionPopup from '@/pages/common/search/position.vue'
import LocationDetailsPopup from '@/pages/common/search/locationDetails.vue'
import RealTimeInfoPopup from '@/pages/common/search/realTimeInfo.vue'
import tab from '@/plugins/tab'

const mapRef = ref<any>()
const mapNavRef = ref<any>(null)
const pointPopupRef = ref<any>(null)


const searchPopupRef = ref<any>(null)
const orderPopupRef = ref<any>(null)
const cartPopupRef = ref<any>(null)

const geodeticRef = ref<any>(null)
const hk1980Ref = ref<any>(null)
const lotglaRef = ref<any>(null)

const tooltipRef = ref<any>(null)
const positionRef = ref<any>(null)
const realTimeInfoRef = ref<any>(null)
const locationDetailsRef = ref<any>(null)
const lotglaListPopupRef = ref<any>(null)
const settingPopupRef = ref<any>(null)


const showCategory = ref(false)
const showMyCenter = ref(false)
const showMyOrder = ref(false)
const showMyCheckout = ref(false)
const showMySetting = ref(false)
const showMyPosition = ref(false)
const detail = ref(null)
const searchList = ref('')

const uploading = ref(false)

// onLoad((options) => {
//   uni.hideTabBar()
// })

// onShow(() => {
//   uni.hideTabBar()
// })

// 监听状态变化
watch(
  [showCategory, showMyCenter, showMyOrder, showMyCheckout,showMySetting],
  (
    [newCategory, newCenter, newOrder, newCheckout, newSetting],
    [oldCategory, oldCenter, oldOrder, oldCheckout,oldSetting],
  ) => {
    if (newCategory==true) {
      searchPopupRef.value?.open()
      positionRef.value?.close()
      mapRef.value?.clearAllMarkers()
      showCategory.value = false;
    }
    if (newSetting==true) {
      settingPopupRef.value?.open()
      showMySetting.value = false;
    }


    if (newCenter==true) {
      showMyCenter.value = false;
      tab.navigateTo('/pages/mine/index')
    }
    if (newOrder==true) {
      orderPopupRef.value?.open()
      showMyOrder.value = false;
    }
    if (newCheckout==true) {
      cartPopupRef.value?.open()
      showMyCheckout.value = false;
    }
  },
  {
    immediate: false,
  },
)

onMounted(() => {
  addMore()
})

// 监听定位状态，开启定位时设置默认回调函数
watch(showMyPosition, (newVal) => {
  if (newVal && mapRef.value) {
    // 使用 nextTick 确保组件已经完全挂载
    nextTick(() => {
      if (mapRef.value) {
        // 设置默认回调函数，确保定位模式下点击图层能显示详细信息
        // 直接复用搜索时的回调逻辑
        const callback = (info: any, mode?: any) => {
          unifiedCallbackFunction(info, mode);
        };
        // 通过 setCallback 方法设置回调函数
        mapRef.value.setCallback(callback);
      }
    });
  }
})

const unifiedCallbackFunction = (info:any,mode?:any)=>{
  if(mode=='geodetic'){
    pointPopupRef.value?.open({STN_NO:info});
    positionRef.value?.close()
    lotglaListPopupRef.value?.close()
  }else if(mode=='searchFor'){
    const info_data = info.data
    lotglaListPopupRef.value?.close()
    pointPopupRef.value?.close()
    positionRef.value?.open()
    mapRef.value?.flyTocenter([info_data.lon, info_data.lat],info_data);
  }else if(mode=='lotgla'){
    HKMAPlotglaByPid(info).then((data:any) => {
      if(data?.rows.length>0){
        const rows = data.rows[0];
        lotglaListPopupRef.value?.open(rows.shortName+" "+rows.geoNo,rows.description,rows.pId);
      }
    }).catch(error => {
        console.error("获取数据失败:", error);
    })
    pointPopupRef.value?.close()
    positionRef.value?.close()
  }
}

const handleHk1980Click = (data: any) => {
  hk1980Ref.value?.close()
  const callback = (e:any,m?:any)=>{
    unifiedCallbackFunction(e,m);
  }
  mapRef.value?.updateHk198({ ...data, 'callback':callback });
}

const handleSearchSClick = (title: any) => {
  uploading.value = true
  HKMAPsearch(title).then((data:any) => {
    const callback = (info:any,mode?:any)=>{
      unifiedCallbackFunction(info,mode);
    }
    searchList.value = data;
    mapRef.value?.updateMarkers('searchFor',data,callback)
    searchPopupRef.value?.close()
    positionRef.value?.open()
    uploading.value = false
  }).catch(error => {
    uploading.value = false
    console.error("获取数据失败:", error);
  })
}
const handlePositionClick = (data: any) => {
  mapRef.value?.flyTocenter([data.lon, data.lat],data);
  // positionRef.value?.close();
}


const handleGeodeticClick = (data: any) => {
  pointPopupRef.value?.open(data)
  geodeticRef.value?.close()
}

const geodeticSearchFor = (key: string, coordinates: any[]) => {
  const callback = (pid:any,mode?:any)=>{
    unifiedCallbackFunction(pid,mode);
  }
  const data = {
    'key':key,
    'coordinates':coordinates,
    'callback':callback
  }
  mapRef.value?.geodeticLanding(data)
}

const lotglaListSearchFor = (data:any,keyIds:any) => {
   const callback = (pid:any,mode?:any)=>{
    unifiedCallbackFunction(pid,mode);
  }
  const info = {
    data:data,
    keyIds:keyIds,
    callback
  }
  mapRef.value?.updatePolygonLotgla(info);
}

const handleLotglaClick = (data: any,key?:any) => {
  lotglaListPopupRef.value?.open(data,key);
}



const handleMapClick = (data: any) => {
  detail.value = data
  pointPopupRef.value?.open(data)
}
const handleMapMClick = (data: any) => {
  pointPopupRef.value?.close()
}

const handleSearchClick = (data: any) => {
  if (data?.name === 'geodetic') {
    searchPopupRef.value?.close()
    geodeticRef.value?.open()
    setTimeout(function() {
      // mapRef.value?.updateMarkers(data?.name)
    }, 300);
  } else if (data?.name === 'hk1980') {
    searchPopupRef.value?.close()
    hk1980Ref.value?.open()
  } else if (data?.name === 'lotgla') {
    searchPopupRef.value?.close()
    lotglaRef.value?.open()
  }
  showCategory.value = false
  // console.log('用户点击了搜索：', data)
}


const handleOrderClick = (data: any) => {
  console.log('用户点击了订单：', data)
}
const handleCartClick = (data: any) => {
  console.log('用户点击了购物车：', data)
}

const handleTooltipClick = (data: any) => {
  console.log('用户点击了：', data)
}

const handlePositionTClick = (data: any) => {
  realTimeInfoRef.value?.open(data)
}

// 处理位置详情显示
const handleLocationDetails = (locationData: any) => {
  console.log('收到位置详情数据:', locationData)
  if (!locationData) {
    locationDetailsRef.value?.close()
  }else{
    locationDetailsRef.value?.open(locationData)
  }

}



const addMore = () => {}

const clearAll = () => {
  mapRef.value?.clearPoints()
}
</script>

<style>
page {
  overflow: hidden;
}
.container {
  width: 100%;
  height: 100vh;
}
</style>
